<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>重置密码</span>
    </div>
    <!-- 表单 -->
    <el-form
      :model="pwdForm"
      :rules="pwdFormRules"
      ref="pwdFormRef"
      label-width="100px"
    >
      <el-form-item label="原密码" prop="oldpwd">
        <el-input v-model="pwdForm.oldpwd" type="password"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newpwd">
        <el-input v-model="pwdForm.newpwd" type="password"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="repwd">
        <el-input v-model="pwdForm.repwd" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updatePwd('pwdFormRef')">修改密码</el-button>
        <el-button @click="resetForm('pwdFormRef')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { updateUserPwdtAPI } from '@/api'
export default {
  name: 'UserPwd',
  data () {
    return {
      // 表单的数据对象
      pwdForm: {
        oldpwd: '',
        newpwd: '',
        repwd: ''
      },
      // 表单的验证规则对象
      pwdFormRules: {
        oldpwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            pattern: /^\S{6,15}$/,
            message: '密码长度必须是6-15位的非空字符串',
            trigger: 'blur'
          }
        ],
        newpwd: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          {
            pattern: /^\S{6,15}$/,
            message: '密码长度必须是6-15位的非空字符串',
            trigger: 'blur'
          }
        ],
        repwd: [
          { required: true, message: '请再次确认新密码', trigger: 'blur' },
          {
            pattern: /^\S{6,15}$/,
            message: '密码长度必须是6-15位的非空字符串',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    updatePwd (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const fd = new URLSearchParams()
          // fd.append('参数名',值)
          fd.append('oldpwd', this.pwdForm.oldpwd)
          fd.append('newpwd', this.pwdForm.newpwd)
          fd.append('repwd', this.pwdForm.repwd)
          const { data: res } = await updateUserPwdtAPI(fd)
          console.log('更改密码的返回', res)
          // const { data: res } = await updateUserPwdtAPI(this.pwdForm)
          if (res.status !== 0) return this.$message.error(res.message)
          this.$message.success(res.message)
          this.$refs[formName].resetFields()
        } else {
          this.$message.error('输入有误，请重新输入')
        }
      })
    },
    // 点击重置按钮，重置表单输入
    resetForm (formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
</style>
